import axios, { AxiosError } from 'axios'
// import { message } from 'antd'
import { showLoading } from './loading'
import { Result } from '@/types/api'
import { message } from './AntdGlobal'
import storage from './storage'

// 创建实例对象
const instance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  timeoutErrorMessage: '请求超时，请稍后再试',
  withCredentials: true
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    showLoading()
    const token = storage.get('token')
    if (token) {
      console.log(token, '设置token')
      config.headers.Authorization = 'Bearer ' + token
    }
    config.headers.icode = '0604CCEDE6E8EE9A'
    return {
      ...config
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(response => {
  const data: Result = response.data
  if (data.code === 500001) {
    message.error(data.msg)
    storage.remove('token')
    location.href = '/login?callback=' + encodeURIComponent(location.href)
  } else if (data.code != 0) {
    if (response.config.showError === false) {
      return Promise.resolve(data)
    } else {
      message.error(data.msg)
      return Promise.reject(data)
    }
  }
  return data.data
})

interface IConfig {
  showLoading?: boolean
  showError?: boolean
}

export default {
  get<T>(url: string, params: any, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
    return instance.get(url, { params, ...options })
  },
  post<T>(url: string, params: any, options: IConfig = { showLoading: true, showError: true }): Promise<T> {
    return instance.post(url, params, options)
  }
}
